package com.module.login.model

import android.text.TextUtils
import cn.leancloud.LCInstallation
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import com.module.app.base.BaseViewModel
import com.module.app.ext.loginFlow
import com.module.app.bean.IType.ILogin
import com.module.base.ext.request
import com.module.base.utils.AppUtils
import com.module.base.utils.CommonUtils
import com.module.base.utils.LogUtils
import com.module.base.utils.ToastUtils
import com.module.frame.ext.postEvent
import com.module.login.R
import com.module.login.utils.loginPush
import com.module.third.learcloud.LCResponse
import com.module.third.learcloud.lcQuerySingle
import com.module.third.learcloud.lcSave

class LoginPhoneViewModel : BaseViewModel() {

    fun isCheck(phone: String): Boolean {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("电话号码不能为空")
            return false
        } else if (!phone.startsWith("1")) {
            ToastUtils.showShort("请输入正确的电话号码格式")
            return false
        }
        return true
    }

    fun login(type: String, id: String, newUserBean: com.module.app.bean.UserBean) {
        request({
            //查询账号
            var response: LCResponse<com.module.app.bean.UserBean> = queryAccount(type, id)
            //判断是否是新号还是已登录过了
            saveUserBean(type, id, newUserBean, response.getData())
        }, {
            check(it != null) {
                CommonUtils.getString(R.string.error_unknow)
            }
            com.module.app.utils.UserUtils.setUserBean(it)
            postEvent(loginFlow, true)
        }, {
            it.msg?.let { msg ->
                ToastUtils.showShort(msg)
            }
        }, true)
    }


    /**
     * 账号查询
     */
    private suspend fun queryAccount(
        @ILogin type: String,
        id: String
    ): LCResponse<com.module.app.bean.UserBean> {
        val tClass = com.module.app.bean.UserBean::class.java
        val query = LCQuery<LCObject>(tClass.simpleName)
        when (type) {
            ILogin.QQ -> query.whereEqualTo("qq", id)
            ILogin.WX -> query.whereEqualTo("wx", id)
            ILogin.PHONE -> query.whereEqualTo("phone", id)
        }
        LogUtils.e("查询账号")
        return lcQuerySingle(query, tClass)
    }

    /**
     * 更新或者上传用户信息
     * @param newUserBean QQ wx登录返回 userBean
     * @param resultUserBean 接口请求后返回的 userBean
     */
    private suspend fun saveUserBean(
        type: String,
        id: String,
        newUserBean: com.module.app.bean.UserBean,
        resultUserBean: com.module.app.bean.UserBean?
    ): LCResponse<com.module.app.bean.UserBean> {
        var userBean: com.module.app.bean.UserBean
        var objectId: String? = null
        //接口返回的为空，则为新号
        if (resultUserBean == null) {
            //数据为空创建账号
            userBean = newUserBean
            if (userBean == null) {
                userBean = com.module.app.bean.UserBean()
            }
            when (type) {
                ILogin.QQ -> {
                    userBean.loginType = ILogin.QQ
                    userBean.qq = id
                }
                ILogin.WX -> {
                    userBean.loginType = ILogin.WX
                    userBean.wx = id
                }
                ILogin.PHONE -> {
                    userBean.loginType = ILogin.PHONE
                    userBean.phone = id
                }
            }
        } else {
            //数据不为空，更新账号  ,更新设备id
            userBean = resultUserBean
            objectId = userBean.objectId
            //如果设备id不是当前设备，则发送推送
            if (userBean.deviceId != null && userBean.deviceId != AppUtils.getAndroidId()) {
                loginPush(userBean.pushId)
            }
        }
        userBean.deviceId = AppUtils.getAndroidId()
        userBean.pushId = LCInstallation.getCurrentInstallation().installationId
        LogUtils.e("更新账号")
        return lcSave(userBean, objectId, com.module.app.bean.UserBean::class.java)
    }
}